import * as Collapsible from "@radix-ui/react-collapsible";
import { ChevronDown } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";

import { LoadingAnimation } from "~/components/deer-flow/loading-animation";
import { Markdown } from "~/components/deer-flow/markdown";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { InterviewStore } from "~/core/store";
import { parseJSON } from "~/core/utils";
import { cn } from "~/lib/utils";

export function ResumeMatcherBlock({
  className,
  messageId,
}: {
  className?: string;
  messageId: string;
}) {
  const messageIds = InterviewStore.useStore(
    useShallow((state) => state.resumeMatcherMessageIds.get(messageId) ?? []),
  );

  const contentRef = useRef<HTMLDivElement>(null);

  return (
    <div
      ref={contentRef}
      className={cn("grid w-full grid-cols-1 gap-4 pt-4 pb-8", className)}
    >
      {messageIds.map((messageId) => (
        <ResumeMatcherItem key={messageId} messageId={messageId} />
      ))}
    </div>
  );
}

function ResumeMatcherItem({ messageId }: { messageId: string }) {
  const message = InterviewStore.useMessage(messageId);
  const [open, setOpen] = useState(true); // 默认展开

  const isSummarize = message?.agent === "resume_matcher_summarize";
  const isToolCalls = !!message?.toolCalls;
  const latestMessageId = InterviewStore.useLatestMessageId(
    "resume_matcher_summarize",
  );
  const isSummarizeContent =
    !!InterviewStore.useMessage(latestMessageId)?.content;

  const resume = useMemo<{
    name?: string;
    score?: number;
    content?: string;
  }>(() => {
    return isSummarize ? {} : parseJSON(message?.content ?? "", {});
  }, [isSummarize, message?.content]);

  if (isSummarizeContent && isToolCalls) {
    return null;
  }

  return (
    <Collapsible.Root open={open} onOpenChange={setOpen} className="w-full">
      <Card>
        <CardHeader className="cursor-pointer px-4">
          <Collapsible.Trigger asChild>
            <CardTitle onClick={() => setOpen(!open)}>
              <div className="flex items-center justify-between">
                {isSummarize ? (
                  <div>匹配汇总</div>
                ) : (
                  <div className="flex items-center gap-5">
                    <div>{resume.name}</div>
                  </div>
                )}
                <ChevronDown
                  className={cn(
                    "size-5 transition-transform duration-200",
                    open ? "rotate-180" : "",
                  )}
                />
              </div>
            </CardTitle>
          </Collapsible.Trigger>
        </CardHeader>

        <Collapsible.Content className="data-[state=open]:animate-slideDown data-[state=closed]:animate-slideUp overflow-hidden">
          <CardContent>
            <Markdown animated checkLinkCredibility>
              {isSummarize ? message.content : resume.content}
            </Markdown>
            {message?.isStreaming && <LoadingAnimation className="my-12" />}
          </CardContent>
        </Collapsible.Content>
      </Card>
    </Collapsible.Root>
  );
}
